package com.feihong.txgw.ui.activity.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.inter.contract.order.IKaikaOrderDetailContract;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.RefreshOrder;
import com.feihong.txgw.model.base_bean.BaseResponse;
import com.feihong.txgw.tx_precenter.KaikaOrderDetailMainPrecenter;
import com.feihong.txgw.ui.activity.kaika.KaiKaActivity;
import com.feihong.txgw.ui.activity.kaika.KaikaDetailInterface;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.feihong.txgw.view.WebView4Scroll;
import com.just.agentweb.AgentWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * @name txgw_app
 * @class name：com.feihong.txgw.ui.activity.order
 * @class describe:  开卡订单详情
 * @author wangziheng
 * @time 2017/8/14 18:58
 * @change
 * @chang time
 * @class describe
 */
public class KaiKaOrderDetailActivity extends BaseMVPCompateActivity<IKaikaOrderDetailContract.AbKaikaOrderDetailMainPrecenter> implements IKaikaOrderDetailContract.IKaikaOrderDetailMainView {
    @BindView(R.id.kaika_order_refreshLayout) SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.kaika_order_content_layout) RelativeLayout mContentLayout;
    private AgentWeb mAgentWeb;
    private String strUrl = "";
    private String orderID = "";
    private String price = "";

    private AgentWeb.PreAgentWeb mPreAgentWeb;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if(activityIsDestory()){
                return;
            }
            if (msg.what == 10) {
                loadPage();
            }
        }
    };

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_kaika_order_layout;
    }

    private void refreshToken() {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                RefreshToken.getInstance().RetrofitRefreshTokenForGet();
                Message message = Message.obtain();
                message.what = 10;
                mHandler.sendMessage(message);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void doPaySuccess(RefreshOrder paySuccessMessage) {
        loadPage();
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        EventBus.getDefault().register(this);
        orderID = getIntent().getStringExtra("orderid");
        if (TextUtils.isEmpty(orderID)) {
            finish();
            return;
        }
        price = getIntent().getStringExtra("price");
        if (TextUtils.isEmpty(price)) {
            price = "0.0";
        }
        setBackButtonFinish();
        setPageTitle("开卡订单详情");


        mRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mRefreshLayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        mRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadPage();
                    }
                }, 200);
            }
        });
        //同步 Cookie
        //AgentWebConfig.syncCookies("http://www.djml.com","ID=XXXX")
//        mRefreshLayout.setRefreshing(true);

        WebView4Scroll webView4Scroll = new WebView4Scroll(getActivity(), mRefreshLayout);
        webView4Scroll.setVerticalScrollBarEnabled(false);
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mContentLayout, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout,R.id.agentweb_re_query_data_layout)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
                .ready();

        refreshToken();
    }

    @Override
    protected void onDestroy() {
        try {
            if (mAgentWeb != null) {
                mAgentWeb.destroy();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if(mHandler != null && mHandler.getLooper() == Looper.getMainLooper()){
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

    @Override
    public void bindData() {

    }

    private void loadPage() {
        HashMap<String, String> map = new HashMap<>();
        map.put("order_id", orderID);
        map.put("table_id", "3");
        strUrl = new SignToken().setSigen(map);
        // Activity用法
        LogUtils.i(TAG,"开卡订单详情url："+ HttpTools.KAIKA_ORDER_DETAIL + "?" + strUrl);
        mAgentWeb = mPreAgentWeb.go(HttpTools.KAIKA_ORDER_DETAIL + "?" + strUrl);
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new KaikaDetailInterface(this, callBack));
        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }
    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    //WebViewClient
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            showSystemToast(url);
            return true;
            // return super.shouldOverrideUrlLoading(view, url);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
            // return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mRefreshLayout.setRefreshing(false);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };
    //WebChromeClient
    private WebChromeClient mWebChromeClient = new WebChromeClient() {

    };

    @Override
    public void cannelKaikaOrderResult(BaseResponse result) {
        if(result.code == 200){
            KaiKaOrderDetailActivity.this.showDialog(null, "取消订单成功", new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    dialogInterface.dismiss();
                    EventBus.getDefault().post(new RefreshOrder());
                    finish();
                }
            });
        }else {
            showDialog(null, result.msg);
        }
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {
        showDialog(null,getString(R.string.connect_service_error));
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return KaikaOrderDetailMainPrecenter.create();
    }

    public class KaiKaOrderJavaScriptInterface {
        @JavascriptInterface
        public void pay_order(String json) {
            try {
                String order_sn = JSON.parseObject(json).getString("order_sn");
                String price = JSON.parseObject(json).getString("price");

                Intent intent = new Intent();
                intent.setClass(KaiKaOrderDetailActivity.this, PayActivity.class);
                intent.putExtra(PayActivity.INTENT_TITLE, "开卡订单");
                intent.putExtra(PayActivity.INTENT_PRICE, price);
                intent.putExtra(PayActivity.INTENT_ORDER_ID, order_sn);
                intent.putExtra(PayActivity.INTENT_PAY_TYPE, PayActivity.PAY_TYPE_KAIKA);
                startActivity(intent);
            } catch (Exception ex) {
                showSystemToast("无法解析数据!");
            }
        }
    }

    private KaikaDetailCallBack callBack = new KaikaDetailCallBack() {
        @Override
        public void pay_order(String payOrder) {
            LogUtils.i(TAG,"开卡订单详情，支付订单："+payOrder);
            try {
                JSONObject jsonObject = new JSONObject(payOrder);
                String price = jsonObject.optString("price");
                String orderSn = jsonObject.optString("order_sn");
                Intent intent = new Intent(KaiKaOrderDetailActivity.this, PayActivity.class);
                intent.putExtra(PayActivity.INTENT_ORDER_ID, orderSn);
                intent.putExtra(PayActivity.INTENT_PRICE, price);
                intent.putExtra(PayActivity.INTENT_PAY_TYPE, PayActivity.PAY_TYPE_KAIKA);
                startActivity(intent);
                finish();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void add_info(String data) {
            LogUtils.i(TAG,"开卡订单详情，持卡开户："+data);
            Intent intent = new Intent(KaiKaOrderDetailActivity.this, KaiKaActivity.class);
            startActivity(intent);
            finish();
        }

        @Override
        public void cancel_order(String cannelOrder) {
            LogUtils.i(TAG,"开卡订单详情，取消订单："+cannelOrder);
            try {
                JSONObject jsonObject = new JSONObject(cannelOrder);
                final String orderSn = jsonObject.optString("order_id");
                showConfirmDialog("取消订单", "您确定要取消此订单信息吗？", "是", "否", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        mPresenter.cannelKaikaOrder(orderSn,String.valueOf(PayActivity.PAY_TYPE_KAIKA));
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    public interface KaikaDetailCallBack {

        void pay_order(String payOrder);  // 补传信息

        void add_info(String data);  //补传信息

        void cancel_order(String cannelOrder);  //  取消订单
    }
}
